package nio;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * Scattering：将数据写入到 buffer 时，可以采用 buffer 数组，依次写入 [分散]
 * Gathering：从 buffer 读取数据时，可以采用 buffer 数组，依次读 [聚合]
 */
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws IOException {
        //使用 ServerSocketChannel 和 SocketChannel 网络
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(9999);
        //绑定端口到 socket，并启动
        serverSocketChannel.socket().bind(inetSocketAddress);
        // 创建 buffer 数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);
        // 等待客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        while (true) {
            socketChannel.read(byteBuffers);
            Arrays.asList(byteBuffers).stream()
                    .forEach(byteBuffer -> System.out.println("position = " + byteBuffer.position() + ", limit: " + byteBuffer.limit()));
            // 将所有 buffer 进行 flip
            Arrays.asList(byteBuffers).stream()
                    .forEach(byteBuffer -> byteBuffer.flip());
            // 读取数据
            socketChannel.write(byteBuffers);
            // 清除数据
            Arrays.asList(byteBuffers).stream()
                    .forEach(byteBuffer -> byteBuffer.clear());
        }
    }
}
